# -*- encoding: utf-8 -*-
from openerp.osv import fields,osv
import math
from openerp.tools import float_is_zero
from openerp import SUPERUSER_ID

class procurement_confirm(osv.osv_memory):
    _inherit = "procurement.confirm"
    #johnw, 12/11, 改为佛山需求生成到中山, 注释下面代码的原来逻辑
#    def confirm(self, cr, uid, ids, context=None):
#        resu = super(procurement_confirm, self).confirm(cr, uid, ids, context=context)
#        #处理同一物料两个公司采购的问题
#        proc_ids = context and context.get('active_ids', [])
#        confirm_id = self.pool.get('procurement.order').read(cr, uid, proc_ids[0], ['confirm_id'])['confirm_id']
#        
#        #1.同一"物料&供应商"的采购明细
#        #同一产品,统一确认批次,存在多条记录,不同公司的数据子表
#        cr.execute('''
#                select c.company_id,b.order_id, c.partner_id, b.id as order_line_id, b.product_id, min(b.product_qty) as order_qty,sum(a.product_qty) as proc_qty_total
#                from procurement_order a
#                join purchase_order_line b on a.purchase_line_id = b.id
#                join purchase_order c on b.order_id = c.id
#                join (select c.partner_id ,b.product_id
#                    from procurement_order a
#                    join purchase_order_line b on a.purchase_line_id = b.id
#                    join purchase_order c on b.order_id = c.id
#                    where a.confirm_id = %s
#                    group by c.partner_id, b.product_id
#                    having count(*) > 1) d 
#                    on c.partner_id = d.partner_id and b.product_id = d.product_id
#                where a.confirm_id = %s
#                group by c.company_id,b.order_id, c.partner_id, b.id, b.product_id
#                ''',(confirm_id,confirm_id,))
#        
#        #2.按照"产品/供应商"归类到dict
#        #order数据
#        prod_order = {}
#        #总理论需求量
#        prod_qty = {}
#        for row in cr.dictfetchall():
#            key = '%s@%s'%(row['product_id'], row['partner_id'])
#            if not prod_order.get(key,[]):
#                prod_order[key] = []
#                prod_qty[key] = {'proc_qty_total':0.0}
#            prod = prod_order.get(key)
#            prod.append(row)
#            prod_qty[key]['proc_qty_total'] = prod_qty[key]['proc_qty_total'] + row.get('proc_qty_total')
#            
#        #3).根据理论需求量和最小包装计算得到: 总采购量
#        prod_obj = self.pool.get('product.product')
#        po_line_obj = self.pool.get('purchase.order.line')
#        comp_zs_id = 3
#        for key, qty in prod_qty.items():
#            product_id, partner_id = key.split("@")
#            product_id = long(product_id)
#            partner_id = long(partner_id)
#            #下面代码参考dmp_pur_prod_supplier
#            prod_supp = prod_obj.get_supplier_product_rec(cr, uid, partner_id,product_id,context=context)
#            if not prod_supp:
#                continue
#            if prod_supp.min_pack_qty:
#                product_qty_base = qty['proc_qty_total']
#                min_pack_qty = prod_supp.min_pack_qty
#                tempvalue = product_qty_base/float(min_pack_qty)
#                if not float_is_zero(math.floor(tempvalue)-tempvalue, precision_rounding=0.00001):
#                    tempvalue=math.ceil(tempvalue)
#                else:
#                    tempvalue=math.floor(tempvalue)
#                #总实际采购量
#                purchase_qty_total = tempvalue*min_pack_qty
#                #根据总理论需求量和总采购量更新采购单: 佛山(1): 采购数量=理论需求量; 中山(3): 采购数量=总采购量-佛山理论需求量
#                order_infos = prod_order.get(key)
#                purchase_qty_zs = purchase_qty_total
#                po_line_id_zs = None
#                for order_info in order_infos:
#                    if not po_line_id_zs and order_info.get('company_id') == comp_zs_id:
#                        po_line_id_zs = order_info['order_line_id']
#                    else:
#                        #佛山: 实际采购数量=理论需求量; 如果有多条中山记录, 其余中山记录(除去po_line_id_zs)也更新为理论需求量
#                        po_line_obj.write(cr, uid, [order_info['order_line_id']], {'product_qty':order_info['proc_qty_total']}, context=context)
#                        purchase_qty_zs -= order_info['proc_qty_total']
#                if not po_line_id_zs and order_info:
#                    #全部为佛山数据, 取最后采购订单行, 此情况不应出现
#                    po_line_id_zs = order_info['order_line_id']
#                    purchase_qty_zs = purchase_qty_zs + order_info['proc_qty_total']
#                #更新中山采购单行的采购数量为:采购数量=总采购量-佛山理论需求量
#                if po_line_id_zs:
#                    po_line_obj.write(cr, uid, [po_line_id_zs], {'product_qty':purchase_qty_zs}, context=context)
#    
#        return resu

class procurement_order(osv.osv):  
    _inherit = "procurement.order"
    #johnw, 12/11, 改为佛山需求生成到中山, 同时存在佛山和中山的采购单草稿, 全部合并到中山
    #dmp_pur_proc中定义的,在make_po的最后调用
    def after_make_po(self, cr, uid, ids, res, context=None):
        #需求单为中山, 检查是否存在佛山采购订单明细, 如果存在则: 将佛山的采购订单明细的需求单合并到中山的采购明细, 佛山的采购订单明细删除, 增加注释到相关两个采购单
        #需求单为佛山, 检查是否存在中山采购订单明细, 如果存在则: 将需求单生成的佛山的采购订单明细的需求单合并到中山的采购明细, 佛山的采购订单明细删除, 增加注释到相关两个采购单
        sql = '''
            select a.id from purchase_order_line a
            join purchase_order b on a.order_id=b.id and b.company_id = %s
            where a.product_id = %s 
            and b.partner_id = %s
            and a.state='draft' 
            and b.state='draft'
            and b.id != %s
            '''  
        res_new = {}
        company_id_zs = 3
        company_id_fs = 1            
        for proc_id, po_id in res.items():
            res_new[proc_id] = po_id
            proc = self.browse(cr, uid, proc_id, context=context)
            comp_id_proc = proc.company_id.id
            #搜索对方公司的相同(产品,供应商)的草稿状态的采购单明细
            #不加上库位,因为佛山和中山采购单的库位肯定不同
            comp_id_search = comp_id_proc == company_id_zs and company_id_fs or company_id_zs
            cr.execute(sql, (comp_id_search, proc.product_id.id, proc.seller_id.id,  po_id))
            po_line_ids = []
            for row in cr.fetchall():
                if row and row[0]:
                    po_line_ids.append(row[0])
            if not po_line_ids:
                continue
            if comp_id_proc == company_id_zs:
                #中山需求单, 将"存在的佛山采购明细"合并到"刚生成的中山采购明细"
                self._po_line_transfer(cr, uid, po_line_ids, proc.purchase_line_id.id)
            if comp_id_proc == company_id_fs:
                #佛山需求单, 将"刚生成的佛山采购明细"合并到"存在的中山采购明细"
                po_new_id = self._po_line_transfer(cr, uid, [proc.purchase_line_id.id], po_line_ids[0])
                #佛山需求单对应采购单变更
                res_new[proc_id] = po_new_id
        return res_new
    
    def _po_line_transfer(self, cr, uid, po_line_ids_from, po_line_id_to, context=None):
        poln_obj = self.pool['purchase.order.line']
        po_obj = self.pool.get('purchase.order')
        po_line_to = poln_obj.browse(cr, uid, po_line_id_to, context=context)
        #增加数量到目标采购单
        cr.execute('select sum(coalesce(product_qty,0)) from purchase_order_line where id in %s',(tuple(po_line_ids_from),))
        row = cr.fetchone()
        qty_trans = row[0] and row[0] or 0.0
        cr.execute('update purchase_order_line set product_qty=product_qty+%s where id = %s',(qty_trans, po_line_id_to))
        #转移源采购明细的需求单连接到目标采购明细
        cr.execute('''
        update procurement_order 
        set purchase_id=%s,
        purchase_line_id = %s,
        target_id = %s
        where purchase_line_id in %s
        ''',(po_line_to.order_id.id, po_line_id_to, '%s,%s'%('purchase.order.line',po_line_id_to), tuple(po_line_ids_from)))     
        #增加message到源和目标采购单 
        for po_line in poln_obj.browse(cr, uid, po_line_ids_from, context=context):
            mess = '佛山北川采购数量移动到中山, 产品: %s ; 源-->目标: %s --> %s ; 数量: %s'\
                    %(po_line.product_id.default_code, po_line.order_id.name, po_line_to.order_id.name, po_line.product_qty)
            po_obj.message_post(cr, uid, po_line.order_id.id, body=mess)
            po_obj.message_post(cr, uid, po_line_to.order_id.id, body=mess)
        #删除原来采购明细
        poln_obj.unlink(cr, SUPERUSER_ID, po_line_ids_from, context=context)
        return po_line_to.order_id.id